# coding:utf-8
from flask import session, g, jsonify
from werkzeug.routing import BaseConverter
from functools import wraps
from ihome.utils.response_code import RET


class RegexConverter(BaseConverter):
    """自定义的接收正则表达式的路由转换器"""
    def __init__(self, url_map, regex):
        """regex是在路由中填写的正则表达式"""
        super(RegexConverter, self).__init__(url_map)
        self.regex = regex


# 登录检测装饰器
def login_required(view_func):
    """检测用户的登录状态"""
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        uid = session.get('uid')
        if uid is not None:
            # 表示用户已经 登录
            # 使用g对象保存uid，在视图函数中可以直接使用
            g.uid = uid
            return view_func(*args, **kwargs)
        else:
            # 用户未登录
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    return wrapper


# 上传图片到七牛云
def upload_image(image_data):
    from qiniu import Auth, put_data
    from config import DevelopmentConfig as AppConfig
    # 构建鉴权对象
    q = Auth(AppConfig.QINIU_ACCESS_KEY, AppConfig.QINIU_SERCET_KEY)
    # 要上传的空间
    bucket_name = AppConfig.QINIU_BUCKET_NAME
    # 生成上传token，可以指定过期时间
    token = q.upload_token(bucket_name, None, 3600)
    result, info = put_data(token, None, image_data)
    if info.status_code == 200:
        return AppConfig.QINIU_URL_DOMAIN + result.get('key')
    else:
        raise Exception('图片上传失败')